package com.chentf.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.chentf.srb.core.mapper.DictMapper;
import com.chentf.srb.core.pojo.dto.ExcelDictDTO;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author chentengfei
 * @desc exceleasy监听器
 * @date 2021-11-07 20:37:42
 */
@Slf4j
@NoArgsConstructor
public class ExcelDictDTOListener extends AnalysisEventListener<ExcelDictDTO> {

    private DictMapper dictMapper;

    //数据列表
    private List<ExcelDictDTO> list = new ArrayList<>();

    //每5条记录批量存储一次数据
    private static final int BATCH_COUNT = 5;

    //通过有参构造方法注入DictMapper
    public ExcelDictDTOListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    @Override
    public void invoke(ExcelDictDTO excelDictDTO, AnalysisContext analysisContext) {
        log.info("解析到每一条记录:{}",excelDictDTO);
        list.add(excelDictDTO);
        //每5条批量插入一次
        if(list.size() >= BATCH_COUNT){
            saveData();
            list.clear();;
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //当最后剩余的数据记录不足BATCH_COUNT时,我们最终一次性存储剩余数据
        saveData();
        log.info("所有数据解析完成!");
    }

    private void saveData(){
        log.info("{} 条数据被存储到数据库......",list.size());
        //调用mapper层的批量save方法:save的是list中存放的对象
        dictMapper.insertBatch(list);
        log.info("{} 条数被存储到数据库成功!",list.size());
    }
}
